package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    //开始时间戳
    private static final long BEGIN_TIMESTAMP = 1640995200L;
    //序列号位数
    private static final int COUNT_BITS = 32;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //long类型64位，不能用字符串拼接因为返回值是long,要用位运算
    //redis自增：时间戳+计数器
    public long nextId(String keyPrefix){
        //生成时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;//秒数

        //生成序列号
        //获取当前日期，精确到天，每天一个key,方便统计订单量
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //UUID策略没有增长的规律
        //自增长,雪花是当前机器自增，内部维护一个机器id，这里是redis自增,不需要维护机器id,更简单
        //雪花算法性能更好，当会有时间回拨问题，redis就没有
        long count = stringRedisTemplate.opsForValue().increment("irc:" + keyPrefix + ":" + date);//每天的key的量允许达到2的32次方

        //拼接并返回
        //时间戳左移32位,或运算拼接count
        return timestamp<<COUNT_BITS | count;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(1970, 1, 1, 0, 0, 0);
        long second = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println("second = " + second);//对应的秒数
    }
}
